package com.mall.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.mall.entity.CategoryBrand;
import com.mall.goods.dao.*;
import com.mall.goods.service.SpuService;
import com.mall.pojo.Brand;
import com.mall.pojo.Category;
import com.mall.pojo.Sku;
import com.mall.pojo.Spu;
import com.mall.util.IdWorker;
import com.mall.vo.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author: bamboo on 20/7/12
 * @description: _
 */
@Service
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private CategoryBrandMapper categoryBrandMapper;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private SkuMapper skuMapper;

    @Override
    public void add(Goods goods) {
//        保存spu
//        主键是雪花id
        long id = idWorker.nextId();
        Spu spu = goods.getSpu();
        spu.setId(String.valueOf(id));
        spu.setStatus(Spu.No_STATUS);
        spuMapper.insertSelective(goods.getSpu());
//        保存sku
        saveSkuList(goods);
    }

    //设置上下架
    /*
     * 商品新增后，审核状态为0（未审核），默认为下架状态。
     * 审核商品，需要校验是否是被删除的商品，如果未删除则修改审核状态为1，并自动上架
     * 下架商品，需要校验是否是被删除的商品，如果未删除则修改上架状态为0
     * 上架商品，需要审核通过的商品
     * 他是这样新增的商品直接给个status=0
     * 上架商品判断已删除报错，下架商品判断已删除也是报错，未删除的状态直接更改其审核状态
     */
    @Override
    public void audit(String id, String status) {
//        根据主键找到sku
        Spu spu = spuMapper.selectByPrimaryKey(id);
//        判断是否删除
        String isDelete = spu.getIsDelete();
        if (isDelete.equals("1")) {
            throw new RuntimeException("已被删除不能审核");
        }
//        否则就保存就前台传递过来的审核状态
        spu.setStatus(status);
        spuMapper.updateByPrimaryKey(spu);
    }

    @Override
    public void pull(String id) {
//        下架商品，需要校验是否是被删除的商品，如果未删除则修改上架状态为0
//        先找到标准产品
        Spu spu = spuMapper.selectByPrimaryKey(id);
//        判断是否删除
        if (spu.getIsDelete().equals("1")) {
            throw new RuntimeException("改商品已删除");
        }
//        否则就下架
        spu.setIsMarketable("0");
        spuMapper.updateByPrimaryKey(spu);
    }

    @Override
    public void put(String id) {
//如果商品审核过了就上架
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (!spu.getStatus().equals("1")) {
            throw new RuntimeException("未审核过的商品不能上架");
        }
        spu.setIsMarketable("1");
        spuMapper.updateByPrimaryKey(spu);
    }

    //批量上架
    @Override
    public int putMany(String[] ids) {
        Spu spu = new Spu();
        String[] str = new String[ids.length];
        System.arraycopy(ids, 0, str, 0, str.length);
        Arrays.copyOf(ids, ids.length, String[].class);
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", Arrays.asList(str));
//        下架
        criteria.andEqualTo("isMarketable", "0");
//        审核通过
        criteria.andEqualTo("status", "1");
//        非删除
        criteria.andEqualTo("isDelete", "0");
        return spuMapper.updateByExampleSelective(spu, example);
    }

    //批量下架
    @Override
    public int spuService(String[] ids) {
        Spu spu = new Spu();
        String[] str = new String[ids.length];
        System.arraycopy(ids, 0, str, 0, str.length);

        return 0;
    }

    private void saveSkuList(Goods goods) {
//spu和sku是一对多的关系
        Spu spu = goods.getSpu();
        Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());
        Date date = new Date();
//使用三级目录
        Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());
//        这里要添加分类和商品的关系
        CategoryBrand categoryBrand = new CategoryBrand();
        categoryBrand.setBrandId(spu.getBrandId());
        categoryBrand.setCategoryId(spu.getCategory3Id());
        int count = categoryBrandMapper.selectCount(categoryBrand);
        if (count == 0) {
            categoryBrandMapper.insert(categoryBrand);
        }

//        现在我们要根据前端给我们的信息去查询到剩下的信息并把它保存在category里面
        List<Sku> skuList = goods.getSkuList();
        if (skuList != null) {
//           遍历skuLis让sku保存每一个数据
            for (Sku sku : skuList) {
                sku.setId(String.valueOf(idWorker.nextId()));
                if (sku.getSpec() == null || "".equals(sku.getSpec())) {
//spec是规格，一个sku对应多个规格
//                    为空就设置{}
                    sku.setSpec("{}");
                }
//                不为空
//              商品的名称  sku的name和spu的name是一样的
                StringBuilder name = new StringBuilder(spu.getName());
//                将规格转换为map，这里的用意应该是确保每一个商品name对应一个规格
//                将json转换为map
                Map<String, String> specMap = JSON.parseObject(sku.getSpec(), Map.class);
                if (specMap != null && specMap.size() > 0) {
                    for (String value : specMap.values()) {
                        name.append("").append(value);
                    }
                }
                sku.setName(name.toString());
                sku.setCreateTime(date);
                sku.setUpdateTime(date);
                sku.setCategoryId(category.getId());
                sku.setCategoryName(category.getName());
                sku.setBrandName(brand.getName());
//                将sku的数据插入到skumapper中
                skuMapper.insertSelective(sku);
            }

        }

    }
}
